import { ref } from 'vue';

export function useDoubleDocCodeGeneration() {
  const generatedCode = ref('');

  const generateSingleDocCode = (formData, tableData) => {
    let code = `
# 程序名称: ${formData.programId}
# 接口函数: ${formData.interfaceFunction}

DATABASE ds

GLOBALS "../../../tiptop/config/top.global"
GLOBALS "../../../tiptop/aws/4gl/aws_ttsrv2_global.4gl"   #TIPTOP Service Gateway 使用的全域變數檔

DEFINE g_forupd_sql    STRING
DEFINE g_fun           RECORD 
        doc_no             LIKE occ_file.occ01
                       END RECORD

################################################################################
# Descriptions...: 接口入口
# Memo...........:
# Usage..........: CALL ${formData.programId}()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${formData.programId}()

 WHENEVER ERROR CONTINUE

    CALL aws_ttsrv_preprocess()    
    
    IF g_status.code = "0" THEN
       CALL ${formData.programId}_process()
    END IF

    CALL aws_ttsrv_postprocess()

END FUNCTION
                       
################################################################################
# Descriptions...: process
# Memo...........:
# Usage..........: CALL ${formData.programId}_process()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${formData.programId}_process()

DEFINE l_sql STRING
TYPE type_detail RECORD
${tableData.map((field, index, array) => {
  const line = `    ${field.field} LIKE  ${field.referenceTableField}`;
  if (index === array.length - 1) {
    return `${line}  #${field.description}`;
  } else {
    return `${line}, #${field.description}`;
  }
}).join('\n')}
END RECORD
DEFINE g_detail type_detail
DEFINE l_sql       STRING
DEFINE l_cnt       smallint
DEFINE l_wc        STRING
DEFINE l_node  om.DomNode

    LET l_sql = "${formData.sql}"
    
    DECLARE ${formData.programId}_curs CURSOR FROM l_sql 
    IF SQLCA.SQLCODE THEN
       LET g_status.code = SQLCA.SQLCODE
       LET g_status.sqlcode = SQLCA.SQLCODE
       RETURN
    END IF

    FOREACH ${formData.programId}_curs INTO ${tableData.map(field => `g_detail.${field.field}`).join(', ')}
        LET l_node = aws_ttsrv_addMasterRecord(base.TypeInfo.create(g_detail), "Master")
    END FOREACH

END FUNCTION
    `;

    generatedCode.value = code;
    return code;
  };

  return {
    generateSingleDocCode,
    generatedCode
  };
}